package com.victor.coder;

import com.victor.common.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/** 数据传输协议
 * Created by DJJ on 2019/3/12.
 */
//对传递过来的数据进行解码,将字节数组转换成请求/响应对象
public class RpcDecoder extends ByteToMessageDecoder {
    private Class<?> genericClass;

    public RpcDecoder(Class<?> genericClass){
        this.genericClass=genericClass;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //消息的长度
        int size = in.readableBytes();
        //保证所有的消息都接收完成
        if (size<4){
            return;
        }
        byte[] bytes=new byte[size];
        //把传递的数据内容读到bytes中
        in.readBytes(bytes);
        //反序列化为对象(RpcDecoder/RpcResponse)
        Object deserialize = SerializationUtil.deserialize(bytes, genericClass);
        //输出对象
        out.add(deserialize);
        //刷新缓存
        ctx.flush();
    }
}
